package com.googlecode.iiddefecttracker.web;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;
import org.springframework.web.servlet.view.RedirectView;

import com.googlecode.iiddefecttracker.domain.Defect;
import com.googlecode.iiddefecttracker.domain.DefectBeanImpl;
import com.googlecode.iiddefecttracker.domain.Project;
import com.googlecode.iiddefecttracker.service.DefectService;
import com.googlecode.iiddefecttracker.service.ProjectService;
import com.googlecode.iiddefecttracker.service.UIService;

/**
 * 
 */
public class DefectFormController extends SimpleFormController {
    
    private final DefectService defectService;
    private final ProjectService projectService;
    private final UIService uiService;
    
    public DefectFormController(final DefectService defectService,
            final ProjectService projectService, final UIService uiService) {
        this.defectService = defectService;
        this.projectService = projectService;
        this.uiService = uiService;
    }
    
    @Override
    protected Object formBackingObject(final HttpServletRequest request)
            throws Exception {
        
        final DefectBeanImpl defect = new DefectBeanImpl();
        
        return defect;
    }
    
    @Override
    protected void initBinder(final HttpServletRequest request,
            final ServletRequestDataBinder binder) throws Exception {
        super.initBinder(request, binder);
        
        binder.setDisallowedFields(new String[] { "project" });
        
        final Defect defect = (Defect) binder.getTarget();
        
        Long projectId = null;
        try {
            projectId = Long.parseLong(request.getParameter("project"));
        } catch (final Exception e) {
            // TODO handle exception
        }
        if (projectId != null) {
            final Project project = projectService.getProjectById(projectId);
            defect.setProject(project);
        }
        
    }
    
    @Override
    protected ModelAndView onSubmit(final Object command) throws Exception {
        
        final Defect defect = (Defect) command;
        
        defectService.saveDefect(defect);
        
        return new ModelAndView(new RedirectView(getSuccessView()));
    }
    
    @Override
    protected Map<Object, Object> referenceData(final HttpServletRequest request)
            throws Exception {
        final Map<Object, Object> dataMap = new HashMap<Object, Object>();
        dataMap.put("projectList", uiService.getAllProjectsForDropdown());
        return dataMap;
    }
    
}
